define(
    'youa.module.price', [
        'can',
        'zepto',
        'underscore',
        'youa.api.getPrices',
        'sf.b2c.mall.framework.comm'
    ],
    function(can, $, _, YOUAGetPrices, SFFrameworkComm) {
        SFFrameworkComm.register(3);
        var offset = $('.header').height() + window.screen.height;
        // var priceModules = $('.cms-module-fillprice')
        var price = can.Control.extend({
            init: function(element, options) {
                this.render(element);
            },
            render: function(element) {
                var that = this;
                var itemIds = this.getItemList();
                // 如果不存在itemid 直接返回
                if (!_.isArray(itemIds) || itemIds.length <= 0) {
                    return false;
                }
                // 渲染
                // can.when(this.requestPrices(itemIds))
                this.requestPrices(itemIds)
                    .done(function(data) {
                        that.renderPrice(data, element);
                        $(element).addClass("price-loaded");
                    })
                    .fail(function(errorCode) {
                        console.error(errorCode);
                    })
            },

            /**
             * [renderPrice 渲染价格]
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            renderPrice: function(data, element) {
                var that = this;
                _.each(data, function(value, key, list) {
                    var itemIds = element.find("[data-cms-itemid='" + value.singelCode + "']")
                    if (itemIds.length && itemIds.length > 1) {
                        _.each(itemIds, function(item) {
                            that.fillPrice($(item), value);
                        })
                    } else {
                        that.fillPrice(itemIds, value);
                    }
                });
            },

            /**
             * [fillPrice 填充价格]
             * @param  {[type]} element [description]
             * @param  {[type]} value   [description]
             * @return {[type]}         [description]
             */
            fillPrice: function(element, value) {
                // 售价
                element.find('.cms-fill-price').text(value.price);
                // 如果原价低于卖价，则不展示折扣和原价
                if (value.price >= value.originPrice || value.originPrice == null) {
                    element.find('.cms-fill-discountparent').hide();
                    element.find('.cms-fill-referencepriceparent').hide();
                } else {
                    element.find('.cms-fill-referenceprice').text(value.originPrice);
                    element.find('.cms-fill-discount').text((parseInt(value.price, 10) * 10 / parseInt(value.originPrice, 10)).toFixed(1));
                }
                // 做售空处理
                if (value.stock <= 0) {
                    element.find(".cms-fill-soldout").show();
                }
            },

            getItemList: function() {
                var $el = this.element.find('.cms-src-item');
                var ids = [];
                _.each($el, function(el) {
                    var id = $(el).attr('data-cms-itemid');
                    if (!_.isEmpty(id)) {
                        ids.push(id);
                    }
                });
                return _.uniq(ids);
            },

            requestPrices: function(itemIds) {
                var itemIdStr = '';
                _.each(itemIds, function function_name(itemId) {
                    itemIdStr = itemIdStr + itemId + ',';
                })
                var request = new YOUAGetPrices({
                    singleCodes: itemIds.join(',')
                    // singleCodes: itemIdStr,
                    // channel: 'Mobile'
                });
                return request.sendRequestRestful();
            },
        });
        var render = function(priceModules) {
            var currentViewTop = $(window).scrollTop(),
                currentViewBottom = currentViewTop + window.screen.height;
            _.each(priceModules, function(priceModule) {
                //上下各预加载一屏幕价格
                var priceModuleTop = $(priceModule).position().top - offset,
                    priceModuleBottom = $(priceModule).position().top + $(priceModule).height() + offset;
                if ($(priceModule).is(":visible") && !$(priceModule).hasClass("price-loaded") && !(
                        priceModuleTop > currentViewBottom)) {
                    // _.defer(function(){
                        new price($(priceModule));
                    // }, 0);

                }
            });
        };


        render($('.cms-module-fillprice'));
        $(window).scroll(function() { render($('.cms-module-fillprice')); });
        $(document).ready(function() { render($('.cms-module-fillprice')); });
        $(document).click(function() { render($('.cms-module-fillprice')); });
    });
